<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .circle-img{
            border: none;
            width: 100px;
            height: 100px;
            border-radius: 50%;
            box-shadow: 5px 5px 5px lightgray;
        }
    </style>
</head>
<body>
<h1>主页</h1>
<p>
    <img class="circle-img"
         id="photoImg"
{#         鼠标指向图片时，显示提示信息#}
         title="点击图片更改"
         onclick="selectImg()"
         src="/static/{% if user.photo %}{{ user.photo }}{% else %}images/default_img.png{% endif %}"/>
</p>
{#创建选择域的对象，还需要其不能显示#}
<input type="file"
       id="selectFile"
       style="display: none"
       onchange="upload(this.files[0])"/>

<h3><a href="{{ url_for('userBlue.modify') }}"/>修改个人信息</h3>
<script>
    function $(domID) {
        return document.getElementById(domID)
    }

    function selectImg() {
        if(confirm('是否确定更改头像')){
            alert('开始准备选择头像')
            $('selectFile').click()
        }
    }

    function upload(file) {
         {#1、test#}
        {#alert(file.type);#}
        {#console.log(file)#}

        if(file.type.startsWith('image/')){
            if(file.size <= 1024*1024*2){

                let url = "{{ url_for('userBlue.upload_photo') }}"
                let request = new XMLHttpRequest()
                request.open('post',url,true)
                request.onload = function (ev){
                    if(request.status==200 && request.readyState==4){
                        respText = request.responseText;
                        // 在后端将接受响应的数据为json类型
                        respJson = JSON.parse(respText)

                        console.log(respText,respJson)
                        $('photoImg').src='/static'+respJson.path
                    }
                }
                let formData = new FormData()
                // 上传文件的key和value
                formData.append('photo', file)

                // 发送请求
                request.send(formData)
            }else{
                alert('上传的图片大小在2M以内')
            }
        }else{
             alert('只限图片上传')
        }
    }
</script>
</body>
</html>